<?php
// includes/auth.php
declare(strict_types=1);
require_once __DIR__ . '/db.php';
session_start();

/**
 * Generate CSRF hidden input
 */
function csrf_field(): string {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return '<input type="hidden" name="csrf_token" value="'.htmlspecialchars($_SESSION['csrf_token']).'">';
}

/**
 * Verify CSRF token
 */
function verify_csrf(): void {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (empty($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
            die('Invalid CSRF token');
        }
    }
}

/**
 * Login function with role support
 */
function auth_login(string $email, string $password): bool {
    global $pdo;

    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND status = 'active' LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user'] = [
            'id' => $user['id'],
            'name' => $user['name'],
            'email' => $user['email'],
            'role' => $user['role']
        ];
        return true;
    }
    return false;
}

/**
 * Get current logged-in user
 */
function current_user(): ?array {
    return $_SESSION['user'] ?? null;
}

/**
 * Require login
 */
function require_login(): void {
    if (!current_user()) {
        header("Location: /jo_cos_system/public/index.php?msg=login_required");
        exit;
    }
}

/**
 * Logout
 */
function logout(): void {
    session_destroy();
    header("Location: /jo_cos_system/public/index.php?msg=logout");
    exit;
}
